﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Reflection;
using System.Windows.Controls;

namespace Ops.Mpc.States
{
    public class EventTrigger : TriggerBase<UIElement>
    {
        #region Fields & Properties
        public static readonly DependencyProperty EventNameProperty = DependencyProperty.Register("EventName", typeof(string), typeof(EventTrigger), null);
        public string EventName
        {
            get
            {
                return (string)this.GetValue(EventNameProperty);
            }

            set
            {
                this.SetValue(EventNameProperty, value);
            }
        }
        #endregion

        #region Constructors
        public EventTrigger()
        {
 
        }

 
        #endregion

        #region Methods

        protected override void OnAttached()
        {

            base.OnAttached();

            Type type = this.AssociatedObject.GetType();
            EventInfo eventInfo = type.GetEvent(this.EventName);

            MethodInfo methodInfo = this.GetType().GetMethod("OnAction", BindingFlags.NonPublic | BindingFlags.Instance);
            eventInfo.AddEventHandler(this.AssociatedObject, Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo));

        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            Type type = AssociatedObject.GetType();
            EventInfo eventInfo = type.GetEvent(this.EventName);

            MethodInfo methodInfo = this.GetType().GetMethod("OnAction", BindingFlags.NonPublic | BindingFlags.Instance);
            eventInfo.RemoveEventHandler(this.AssociatedObject, Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo));

        }

        private void OnAction(object sender, EventArgs e)
        {
            FrameworkElement frameworkElement = AssociatedObject as FrameworkElement;

            if (frameworkElement != null)
                InvokeActions(frameworkElement.DataContext);
            else
                InvokeActions(AssociatedObject);
        }

  
        #endregion



    }

}
